/**
  ******************************************************************************
  * @file    main.c
  * @author  MCU Application Team
  * @brief   Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2023 Puya Semiconductor Co.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by Puya under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "py32md530xx_ll_Start_Kit.h"

/* Private define ------------------------------------------------------------*/
#define ADC_CALIBRATION_TIMEOUT_MS         5
#define VAR_CONVERTED_DATA_INIT_VALUE      (__LL_ADC_DIGITAL_SCALE(LL_ADC_RESOLUTION_12B) + 1)
#define VDDA_APPLI                         ((uint32_t)3300)

/* Private variables ---------------------------------------------------------*/
__IO uint32_t wait_loop_index = 0;
__IO uint32_t ADCxConvertedDatas[4];
__IO uint16_t uhADCxConvertedData_Voltage_mVolt = 0;

/* Private user code ---------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
static void APP_SystemClockConfig(void);
static void APP_AdcConfig(void);
static void APP_DmaConfig(void);
static void APP_TimConfig(void);
static void APP_AdcCalibrate(void);
static void APP_AdcEnable(void);

/**
  * @brief  Main program.
  * @param  None
  * @retval int
  */
int main(void)
{
  /* Enable SYSCFG and PWR clock */
  LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_SYSCFG);
  LL_APB1_GRP1_EnableClock(LL_APB1_GRP1_PERIPH_PWR);

  /* Configure system clock */
  APP_SystemClockConfig();

  /* Initialize UART (for printf use) */
  BSP_UART_Config();

  /* DMA configuration */
  APP_DmaConfig();

  /* ADC configuration */
  APP_AdcConfig();

  /* ADC Calibrate */
  APP_AdcCalibrate();
  
  /* ADC Enable */
  APP_AdcEnable();

  /* ADC Start */
  LL_ADC_REG_StartConversion(ADC1);

  /* Tim Config */
  APP_TimConfig();

  while (1)
  {
  }
}


/**
  * @brief  DMA transfer completion callback function
  * @param  None
  * @retval None
  */
void APP_TransferCompleteCallback(void)
{
  /*Convert ADC sampling values to voltage values*/
  uhADCxConvertedData_Voltage_mVolt = __LL_ADC_CALC_DATA_TO_VOLTAGE(VDDA_APPLI, ADCxConvertedDatas[0], LL_ADC_RESOLUTION_12B);
  printf("%s%s%u mV\r\n","Channel4","Voltage:",uhADCxConvertedData_Voltage_mVolt);
  
  /*Convert ADC sampling values to voltage values*/
  uhADCxConvertedData_Voltage_mVolt = __LL_ADC_CALC_DATA_TO_VOLTAGE(VDDA_APPLI, ADCxConvertedDatas[1], LL_ADC_RESOLUTION_12B);
  printf("%s%s%u mV\r\n","Channel5","Voltage:",uhADCxConvertedData_Voltage_mVolt);
  
  /*Convert ADC sampling values to voltage values*/
  uhADCxConvertedData_Voltage_mVolt = __LL_ADC_CALC_DATA_TO_VOLTAGE(VDDA_APPLI, ADCxConvertedDatas[2], LL_ADC_RESOLUTION_12B);
  printf("%s%s%u mV\r\n","Channel6","Voltage:",uhADCxConvertedData_Voltage_mVolt);
  
  /*Convert ADC sampling values to voltage values*/
  uhADCxConvertedData_Voltage_mVolt = __LL_ADC_CALC_DATA_TO_VOLTAGE(VDDA_APPLI, ADCxConvertedDatas[3], LL_ADC_RESOLUTION_12B);
  printf("%s%s%u mV\r\n\r\n","Channel7","Voltage:",uhADCxConvertedData_Voltage_mVolt);
}

/**
  * @brief  ADC calibration function.
  * @param  None
  * @retval None
  */
static void APP_AdcCalibrate()
{
  #if (USE_TIMEOUT == 1)
  uint32_t Timeout = 0; /* Variable used for timeout management */
  #endif /* USE_TIMEOUT */
  
  if (LL_ADC_IsEnabled(ADC1) == 0)
  { 
    /* Clear EOCAL */
    LL_ADC_ClearFlag_EOCAL(ADC1);
 
    LL_ADC_StartCalibration(ADC1,LL_ADC_CALIBRATION_NUMBER_1);
    
    /* Poll for ADC effectively calibrated */
    #if (USE_TIMEOUT == 1)
    Timeout = ADC_CALIBRATION_TIMEOUT_MS;
    #endif /* USE_TIMEOUT */
    
    while (LL_ADC_IsActiveFlag_EOCAL(ADC1) != 1)
    {
    #if (USE_TIMEOUT == 1)
      /* Check Systick counter flag to decrement the time-out value */
      if (LL_SYSTICK_IsActiveCounterFlag())
      {
        if(Timeout-- == 0)
        {
          APP_ErrorHandler();
        }
      }
    #endif /* USE_TIMEOUT */
    } 

    wait_loop_index = (LL_ADC_DELAY_CALIB_ENABLE_ADC_CYCLES >> 1);
    while(wait_loop_index != 0)
    {
      wait_loop_index--;
    }
  }
}

/**
  * @brief  ADC Enable
  * @param  None
  * @retval None
  */
static void APP_AdcEnable(void)
{
  LL_ADC_ClearFlag_ADRDY(ADC1); 

  /* Enable ADC */
  LL_ADC_Enable(ADC1);

  while(LL_ADC_IsActiveFlag_ADRDY(ADC1)==0);
}

/**
  * @brief  TIM Config function
  * @param  None
  * @retval None
  */
static void APP_TimConfig(void)
{
  /* Enable TIM1 clock */
  LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_TIM1);

  /* Set TIM1 prescaler */
  LL_TIM_SetPrescaler(TIM1,2000);

  /* Set TIM1 auto-reload value */
  LL_TIM_SetAutoReload(TIM1, 4000);

  /* Set TIM1 update trigger */
  LL_TIM_SetTriggerOutput(TIM1,LL_TIM_TRGO_UPDATE);

  /* Enable TIM1 */
  LL_TIM_EnableCounter(TIM1);
}

/**
  * @brief ADC1 Config Function
  * @param None
  * @retval None
  */
static void APP_AdcConfig(void)
{
  /* Set ADC Clock Source Sysclk */
  LL_RCC_SetADCClockSource(LL_RCC_ADC_CLKSOURCE_SYSCLK);
  
  /* Enable ADC1 clock */
  LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_ADC1);

  /* Enable GPIOA clock */
  LL_IOP_GRP1_EnableClock(LL_IOP_GRP1_PERIPH_GPIOA);

  /* Configure pins PA4/5/6/7 as analog */
  LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_4, LL_GPIO_MODE_ANALOG);
  LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_5, LL_GPIO_MODE_ANALOG);
  LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_6, LL_GPIO_MODE_ANALOG);
  LL_GPIO_SetPinMode(GPIOA, LL_GPIO_PIN_7, LL_GPIO_MODE_ANALOG);

  LL_ADC_SetDataAlignment(ADC1,LL_ADC_DATA_ALIGN_RIGHT);                                     /* DataAlignment Right */
  LL_ADC_SetResolution(ADC1,LL_ADC_RESOLUTION_12B);                                          /* Resolution 12 */
  LL_ADC_SetLowPowerMode(ADC1,LL_ADC_LP_MODE_NONE);                                          /* LowPowerMode None */

  LL_ADC_REG_SetTriggerSource(ADC1,LL_ADC_REG_TRIG_EXT_TIM1_TRGO);                           /* Trigger TIM1_TRGO */
  LL_ADC_REG_SetSequencerLength(ADC1,LL_ADC_REG_SEQ_SCAN_ENABLE_4RANKS);                     /* Scan 4 Ranks */
  LL_ADC_REG_SetDMATransfer(ADC1,LL_ADC_REG_DMA_TRANSFER_UNLIMITED);                         /* DMA transfer unlimited */ 
  LL_ADC_REG_SetContinuousMode(ADC1,LL_ADC_REG_CONV_SINGLE);                                 /* Mode Single */
  LL_ADC_REG_SetOverrun(ADC1,LL_ADC_REG_OVR_DATA_OVERWRITTEN);                               /* Overrun overwriten*/

  LL_ADC_SetCommonClock(__LL_ADC_COMMON_INSTANCE(ADC1), LL_ADC_CLOCK_SYNC_PCLK_DIV4);        /* Clock Sync Pclk div4 */

  LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_1, LL_ADC_CHANNEL_4);                  /* Channel CHANNEL_4 */
  LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_2, LL_ADC_CHANNEL_5);                  /* Channel CHANNEL_5 */
  LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_3, LL_ADC_CHANNEL_6);                  /* Channel CHANNEL_6 */
  LL_ADC_REG_SetSequencerRanks(ADC1, LL_ADC_REG_RANK_4, LL_ADC_CHANNEL_7);                  /* Channel CHANNEL_7 */

  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_4, LL_ADC_SAMPLINGTIME_640CYCLES_5);   /* Sampletime 640.5 */
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_5, LL_ADC_SAMPLINGTIME_640CYCLES_5);   /* Sampletime 640.5 */
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_6, LL_ADC_SAMPLINGTIME_640CYCLES_5);   /* Sampletime 640.5 */
  LL_ADC_SetChannelSamplingTime(ADC1, LL_ADC_CHANNEL_7, LL_ADC_SAMPLINGTIME_640CYCLES_5);   /* Sampletime 640.5 */
}

/**
  * @brief Dma Config Function
  * @param None
  * @retval None
  */
static void APP_DmaConfig(void)
{
  LL_DMA_InitTypeDef DMA_InitStruct = {0};

  /* Enable DMA clock */
  LL_AHB1_GRP1_EnableClock(LL_AHB1_GRP1_PERIPH_DMA1);

  LL_APB1_GRP2_EnableClock(LL_APB1_GRP2_PERIPH_SYSCFG);

  /* DMA Channel1 Map to ADC */
  LL_SYSCFG_SetDMARemap(DMA1, LL_DMA_CHANNEL_1, LL_SYSCFG_DMA_MAP_ADC);

  DMA_InitStruct.PeriphOrM2MSrcAddress    =  (uint32_t)&ADC1->DR;                       
  DMA_InitStruct.MemoryOrM2MDstAddress    =  (uint32_t)&ADCxConvertedDatas;
  DMA_InitStruct.Direction                =  LL_DMA_DIRECTION_PERIPH_TO_MEMORY;     /* Configure DMA transmission direction to peripheral to memory */
  DMA_InitStruct.PeriphOrM2MSrcIncMode    =  LL_DMA_PERIPH_FIX;                     /* Configure DMA peripheral address unchanged mode */
  DMA_InitStruct.MemoryOrM2MDstIncMode    =  LL_DMA_MEMORY_INCREMENT;               /* Configure DMA storage address increment mode */ 
  DMA_InitStruct.PeriphOrM2MSrcDataSize   =  LL_DMA_PDATAALIGN_WORD;                /* Configure DMA peripheral transmission method as word */
  DMA_InitStruct.MemoryOrM2MDstDataSize   =  LL_DMA_MDATAALIGN_WORD;                /* Configure DMA memory transfer method as word */
  DMA_InitStruct.Mode                     =  LL_DMA_MODE_INFINITE_CIRCULAR;         /* Configure DMA mode INFINITE_CIRCULAR*/
  DMA_InitStruct.Priority                 =  LL_DMA_PRIORITY_0;                     /* Configure DMA priority to 0 */
  DMA_InitStruct.TransMode                =  LL_DMA_TRANSFER_SINGLE;
  DMA_InitStruct.NbData = 4;                                                        /* Configure DMA transmission length to 4 */
 
  /* DMA initialization */
  LL_DMA_Init(DMA1,LL_DMA_CHANNEL_1,&DMA_InitStruct);              

  /* Enable DMA block transfer interruption: transfer complete */
  LL_DMA_EnableIT_BTC(DMA1,LL_DMA_CHANNEL_1);

  NVIC_SetPriority(DMA1_Channel1_IRQn, 0);
  NVIC_EnableIRQ(DMA1_Channel1_IRQn);
    
  /* Enable the DMA transfer */
  LL_DMA_EnableChannel(DMA1,LL_DMA_CHANNEL_1);
}

/**
  * @brief  Configure system clock
  * @param  None
  * @retval None
  */
static void APP_SystemClockConfig(void)
{
  /* Enable HSI */
  LL_RCC_HSI_Enable();
  while(LL_RCC_HSI_IsReady() != 1)
  {
  }

  /* Set AHB prescaler: HCLK = SYSCLK */
  LL_RCC_SetAHBPrescaler(LL_RCC_SYSCLK_DIV_1);

  /* Select HSISYS as system clock source */
  LL_RCC_SetSysClkSource(LL_RCC_SYS_CLKSOURCE_HSISYS);
  while(LL_RCC_GetSysClkSource() != LL_RCC_SYS_CLKSOURCE_STATUS_HSISYS)
  {
  }

  /* Set APB prescaler: PCLK = HCLK */
  LL_RCC_SetAPB1Prescaler(LL_RCC_APB1_DIV_1);
  LL_Init1msTick(8000000);

  /* Update the SystemCoreClock global variable(which can be updated also through SystemCoreClockUpdate function) */
  LL_SetSystemCoreClock(8000000);
}

/**
  * @brief  Error executing function.
  * @param  None
  * @retval None
  */
void APP_ErrorHandler(void)
{
  while (1)
  {
  }
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* Users can add their own printing information as needed,
     for example: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* Infinite loop */
  while (1)
  {
  }
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT Puya *****END OF FILE******************/
